{% extends "base.html" %}
{% block title %}Search results for "{{query}}", classified with {{model.name}}{% endblock %}
{% block head %}
  <style type="text/css">
    .category {
      float: left;
      width: 30%;
      border: 1px solid black;
      margin: 5px;
    }
  </style>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
  <script type="text/javascript" src="/static/json2.js"></script>
  <script type="text/javascript">
    function get_new_tweets(since) {
      data = {
        "q": "{{query|escape}}",
      };
      if(since != undefined)
        data["since"] = since;
      $.ajax({
        dataType: "jsonp",
        url: "http://search.twitter.com/search.json",
        data: data,
        success: function(msg) {
          classify_tweets(msg.results);
        },
      });
    }

    function classify_tweets(tweets) {
      $.ajax({
        type: "POST",
        url: "/classify/{{model_id}}",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(tweets),
        success: function(tweets) {
          add_tweets(tweets);
        },
      });
    }
    
    function add_tweets(tweets) {
      for(var idx in tweets) {
        tweet = tweets[idx];
        category = $("#category-" + tweet.category + " .tweets");
        markup = create_tweet_markup(tweet);
        category.prepend(markup)
      }
    }
    
    function create_tweet_markup(tweet) {
        markup = $('<div class="tweet"></div>');
        markup.append($("<p />", {text: tweet.text}));
        markup.append($("<div />", {
            text: "by " + tweet.from_user,
            class: "author"
        }));
        return markup;
    }

    $(function(){
      get_new_tweets();
    });
  </script>
{% endblock %}
{% block body %}
  <h1>Search results for "{{query}}", classified with {{model.name}}</h1>
  {% for category in model.category_tuples %}
    <div class="category" id="category-{{category.0}}">
      <h2>{{category.1|escape}}</h2>
      <div class="tweets">
      </div>
    </div>
  {% endfor %}
{% endblock %}
